/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.replenishment.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.express.entity.Express;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.ordersstore.entity.OrdersStore;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.replenishment.entity.Replenishment;
import com.jeeplus.modules.replenishment.service.ReplenishmentService;

/**
 * 补货申请Controller
 * @author w
 * @version 2021-09-16
 */
@Controller
@RequestMapping(value = "${adminPath}/replenishment/replenishment")
public class ReplenishmentController extends BaseController {

	@Autowired
	private ReplenishmentService replenishmentService;
	
	@ModelAttribute
	public Replenishment get(@RequestParam(required=false) String id) {
		Replenishment entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = replenishmentService.get(id);
		}
		if (entity == null){
			entity = new Replenishment();
		}
		return entity;
	}
	
	/**
	 * 补货申请列表页面
	 */
	@RequiresPermissions("replenishment:replenishment:list")
	@RequestMapping(value = {"list", ""})
	public String list(Replenishment replenishment, Model model) {
		model.addAttribute("replenishment", replenishment);
		return "modules/replenishment/replenishmentList";
	}
	
		/**
	 * 补货申请列表数据
	 */
	@ResponseBody
	@RequiresPermissions("replenishment:replenishment:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Replenishment replenishment, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Replenishment> page = replenishmentService.findPage(new Page<Replenishment>(request, response), replenishment); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑补货申请表单页面
	 */
	@RequiresPermissions(value={"replenishment:replenishment:view","replenishment:replenishment:add","replenishment:replenishment:edit"},logical=Logical.OR)
	@RequestMapping(value = "form/{mode}")
	public String form(@PathVariable String mode, Replenishment replenishment, Model model) {
		model.addAttribute("replenishment", replenishment);
		model.addAttribute("mode", mode);
		return "modules/replenishment/replenishmentForm";
	}

	/**
	 * 保存补货申请
	 */
	@ResponseBody
	@RequiresPermissions(value={"replenishment:replenishment:add","replenishment:replenishment:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Replenishment replenishment, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(replenishment);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		replenishmentService.save(replenishment);//保存
		j.setSuccess(true);
		j.setMsg("保存补货申请成功");
		return j;
	}
	
	/**
	 * 删除补货申请
	 */
	@ResponseBody
	@RequiresPermissions("replenishment:replenishment:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Replenishment replenishment) {
		AjaxJson j = new AjaxJson();
		replenishmentService.delete(replenishment);
		j.setMsg("删除补货申请成功");
		return j;
	}
	
	/**
	 * 批量删除补货申请
	 */
	@ResponseBody
	@RequiresPermissions("replenishment:replenishment:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			replenishmentService.delete(replenishmentService.get(id));
		}
		j.setMsg("删除补货申请成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("replenishment:replenishment:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(Replenishment replenishment, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "补货申请"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Replenishment> page = replenishmentService.findPage(new Page<Replenishment>(request, response, -1), replenishment);
    		new ExportExcel("补货申请", Replenishment.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出补货申请记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("replenishment:replenishment:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Replenishment> list = ei.getDataList(Replenishment.class);
			for (Replenishment replenishment : list){
				try{
					replenishmentService.save(replenishment);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条补货申请记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条补货申请记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入补货申请失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入补货申请数据模板
	 */
	@ResponseBody
	@RequiresPermissions("replenishment:replenishment:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "补货申请数据导入模板.xlsx";
    		List<Replenishment> list = Lists.newArrayList(); 
    		new ExportExcel("补货申请数据", Replenishment.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }


	/**
	 * 发货
	 */
	@RequiresPermissions(value={"replenishment:replenishment:express"})
	@RequestMapping(value = "express")
	public String express(Replenishment replenishment, Model model) {
		model.addAttribute("replenishment", replenishment);
		return "modules/replenishment/addExpress";
	}


	/**
	 * 保存补货申请
	 */
	@ResponseBody
	@RequestMapping(value = "saveExpress")
	public AjaxJson save(Replenishment replenishment) {
		AjaxJson j = new AjaxJson();
		try {
			if ("1".equals(replenishment.getRemarks()) || "1".equals(replenishment.getShipped())){
				j.setSuccess(false);
				j.setMsg("申请已发货或已取消");
				return j;
			}
			replenishmentService.saveExpress(replenishment);//保存
			j.setSuccess(true);
			j.setMsg("发货成功");
		}catch (Exception e){
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg(e.getMessage());
		}
		return j;
	}


	/**
	 * 取消发货
	 */
	@ResponseBody
	@RequiresPermissions("replenishment:replenishment:express")
	@RequestMapping(value = "cancelExpress")
	public AjaxJson cancelExpress(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			replenishmentService.cancel(replenishmentService.get(id));
		}
		j.setMsg("取消发货成功");
		return j;
	}

	/**
	 * 确认发货，2022-1-22该批量不填发货信息，上面的发货保存发货不用了
	 */
	@ResponseBody
	@RequiresPermissions("replenishment:replenishment:express")
	@RequestMapping(value = "confirmExpress")
	public AjaxJson confirmExpress(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			replenishmentService.confirmSend(replenishmentService.get(id));
		}
		j.setMsg("发货成功");
		return j;
	}

}